package com.tianji.learning.service.impl;

import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.SignResultVO;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

import static com.tianji.learning.constants.RedisConstants.SIGN_RECORD_KEY_PREFIX;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author gml
 * @since 2024-06-29
 */
@Service
@RequiredArgsConstructor
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    private final StringRedisTemplate redisTemplate;
    /**
     * 签到
     * @return
     */
    @Override
    public SignResultVO sign() {
        //1.签到
        //1.1获取用户id
        Long user = UserContext.getUser();
        //1.2获取当前时间
        LocalDate now = LocalDate.now();
        //1.3拼接key
        String key = SIGN_RECORD_KEY_PREFIX
                + user
                + now.format(DateUtils.SIGN_DATE_SUFFIX_FORMATTER);
        //1.4计算偏差值
        int offset = now.getDayOfMonth() - 1;
        //1.5往redis添加签到记录
        Boolean exists = redisTemplate.opsForValue().setBit(key, offset, true);
        if (exists){
            throw new BizIllegalException("今天已经签到过了");
        }

        //2.计算连续签到天数

        return null;
    }
}
